package com.help10000.rms.mvp.presenter

import android.util.Log
import com.amir.common.api.CustomObserver
import com.amir.common.mvp.model.Model
import com.amir.common.mvp.presenter.BasePresenter
import com.amir.common.utils.Constant
import com.amir.common.utils.SPUtils
import com.amir.common.utils.ToastUtil
import com.amir.common.utils.Utils
import com.google.gson.JsonElement
import com.help10000.rms.mvp.view.RefuseView
import com.help10000.rms.ui.activitys.RefuseOrderActivity
import com.help10000.rms.utils.LocationManager
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch

class RefusePresenter(view: RefuseView) : BasePresenter<RefuseView>(view) {
    // 自定义协程作用域，绑定生命周期（Job用于取消）
    private val coroutineScope = CoroutineScope(Dispatchers.Main + Job())

    fun submit(repairId: String?, reason: String,activity:RefuseOrderActivity) {
        if (reason.isBlank()) {
            ToastUtil.show("请输入拒绝理由")
            return
        }
        coroutineScope.launch(Dispatchers.IO){
            val (lat, lng) = LocationManager.getLocation(activity)
            Log.d("拒绝订单定位", "获取到经纬度：lat=$lat, lng=$lng")


            val AccessToken = SPUtils.getString(Constant.AccessToken)
            val Latitude = lat
            val Longitude = lng

            val refuseOrder = Model.getServer().refuseOrder(
                AccessToken,
                repairId,
                Latitude = Latitude!!,
                Longitude = Longitude!!,
                reason,
            )
            Model.getObservable(refuseOrder, object : CustomObserver<JsonElement>(mvpView) {
                override fun success(t: JsonElement) {
                    coroutineScope.launch(Dispatchers.Main) {
                        mvpView?.refuseSuccess()
                    }
                }
            })
        }
    }
    // 在Presenter销毁时调用，取消所有协程
    fun onDestroy() {
        coroutineScope.cancel()
    }

}
